/* **************************************************
 Copyright (c) 2012, University of Cambridge
 Neal Lathia, neal.lathia@cl.cam.ac.uk
 Kiran Rachuri, kiran.rachuri@cl.cam.ac.uk

This library was developed as part of the EPSRC Ubhave (Ubiquitous and
Social Computing for Positive Behaviour Change) Project. For more
information, please visit http://www.emotionsense.org

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ************************************************** */

package com.ubhave.sensormanager.sensors.pull;

import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.config.GlobalConfig;
import com.ubhave.sensormanager.config.pull.BluetoothConfig;
import com.ubhave.sensormanager.config.pull.PullSensorConfig;
import com.ubhave.sensormanager.data.pull.BluetoothData;
import com.ubhave.sensormanager.data.pull.ESBluetoothDevice;
import com.ubhave.sensormanager.process.pull.BluetoothProcessor;
import com.ubhave.sensormanager.sensors.SensorUtils;
import com.ubhave.sensormanager.utils.LogUtil;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.app.Context;
import ohos.bluetooth.BluetoothHost;
import ohos.bluetooth.BluetoothRemoteDevice;
import ohos.event.commonevent.*;
import ohos.rpc.RemoteException;

import java.util.ArrayList;

public class BluetoothSensor extends AbstractPullSensor {
    private static final String TAG = "BluetoothSensor";
    //BlueTooth非敏感权限，不用ask
    private static final String[] REQUIRED_PERMISSIONS = new String[]{
            "ohos.permission.USE_BLUETOOTH",
            "ohos.permission.DISCOVER_BLUETOOTH",
            "ohos.permission.LOCATION"
    };

    private volatile static BluetoothSensor bluetoothSensor;
    private static Object lock = new Object();

    private ArrayList<ESBluetoothDevice> btDevices;
    private BluetoothHost bluetooth = null;

    private int cyclesRemaining, sensorStartState;
    private BluetoothData bluetoothData;
    private CommonEventSubscriber receiver;

    public static BluetoothSensor getSensor(final Context context) throws ESException {
        BluetoothSensor localBluetoothSensor = bluetoothSensor;
        if (localBluetoothSensor == null) {
            synchronized (lock) {
                localBluetoothSensor = bluetoothSensor;
                if (localBluetoothSensor == null) {
                    if (allPermissionsGranted(context, REQUIRED_PERMISSIONS)) {
                        bluetoothSensor = localBluetoothSensor = new BluetoothSensor(context);
                    } else {
                        throw new ESException(ESException.PERMISSION_DENIED, SensorUtils.SENSOR_NAME_BLUETOOTH);
                    }
                }
            }
        }
        return bluetoothSensor;
    }

    private BluetoothSensor(final Context context) {
        super(context);
        btDevices = new ArrayList<ESBluetoothDevice>();
        bluetooth = BluetoothHost.getDefaultHost(context);
        if (bluetooth == null) {
            if (GlobalConfig.shouldLog()) {
                LogUtil.loge(TAG, "Device does not support Bluetooth");
            }
            return;
        }

        // Create a BroadcastReceiver for ACTION_FOUND, sent when a device is discovered
        MatchingSkills skills = new MatchingSkills();

//        IntentFilter found = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//        IntentFilter finished = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        skills.addEvent(BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED);
        skills.addEvent(BluetoothHost.EVENT_HOST_DISCOVERY_STARTED);
        skills.addEvent(BluetoothHost.EVENT_HOST_DISCOVERY_FINISHED);
        CommonEventSubscribeInfo info = new CommonEventSubscribeInfo(skills);
        receiver = new CommonEventSubscriber(info) {
            @Override
            public void onReceiveEvent(CommonEventData data) {
                if (data == null) {
                    return;
                }
                Intent info = data.getIntent();
                if (info == null) {
                    return;
                }
                //获取系统广播的action
                String action = info.getAction();
                //判断是否为扫描到设备的广播
                if (BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED.equals(action)) {
                    IntentParams myParam = info.getParams();
                    BluetoothRemoteDevice device = (BluetoothRemoteDevice) myParam.getParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE);
                    String deviceAddr = device.getDeviceAddr();
                    String deviceName = null;
                    if (device.getDeviceName() != null && device.getDeviceName().isPresent()) {
                        deviceName = device.getDeviceName().get();
                    }
                    int rssi = 0; //BluetoothHost.EXTRA_RSSI 暂无

                    ESBluetoothDevice esBluetoothDevice = new ESBluetoothDevice(System.currentTimeMillis(), deviceAddr, deviceName, rssi);
                    if (!(btDevices.contains(esBluetoothDevice))) {
                        btDevices.add(esBluetoothDevice);
                    }

                } else if (BluetoothHost.EVENT_HOST_DISCOVERY_FINISHED.equals(action)) {
                    cyclesRemaining -= 1;
                    if (cyclesRemaining > 0) {
                        bluetooth.startBtDiscovery();
                    } else {
                        notifySenseCyclesComplete();
                    }
                }
            }
        };
    }

    protected String getLogTag() {
        return TAG;
    }

    public int getSensorType() {
        return SensorUtils.SENSOR_TYPE_BLUETOOTH;
    }

    protected BluetoothData getMostRecentRawData() {
        return bluetoothData;
    }

    private boolean shouldForceEnable() {
        try {
            return (Boolean) sensorConfig.getParameter(BluetoothConfig.FORCE_ENABLE_SENSOR);
        } catch (Exception e) {
            e.printStackTrace();
            return BluetoothConfig.DEFAULT_FORCE_ENABLE;
        }
    }

    protected void processSensorData() {
        BluetoothProcessor processor = (BluetoothProcessor) getProcessor();
        bluetoothData = processor.process(pullSenseStartTimestamp, btDevices, sensorConfig.clone());
    }

    protected boolean startSensing() {
        btDevices.clear();
        sensorStartState = bluetooth.getBtState();
        if (bluetooth.getBtState() == BluetoothHost.STATE_OFF && shouldForceEnable()) {
            bluetooth.enableBt();
            while (bluetooth.getBtState() == BluetoothHost.STATE_OFF) {
                try {
                    Thread.sleep(100);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        }

        if (bluetooth.getBtState() == BluetoothHost.STATE_ON) {
            cyclesRemaining = (Integer) sensorConfig.getParameter(PullSensorConfig.NUMBER_OF_SENSE_CYCLES);

            // Register the BroadcastReceiver: note that this does NOT start a scan
            try {
                CommonEventManager.subscribeCommonEvent(receiver);
            } catch (IllegalArgumentException | RemoteException e) {
                // Receiver not registered
            }

            bluetooth.startBtDiscovery();
            return true;
        } else {
            if (GlobalConfig.shouldLog()) {
                LogUtil.loge(TAG, "Bluetooth is not enabled.");
            }
            return false;
        }
    }

    // Called when a scan is finished
    protected void stopSensing() {
        if (bluetooth != null) {
            bluetooth.cancelBtDiscovery();
            if (sensorStartState == BluetoothHost.STATE_OFF) {
                bluetooth.disableBt();
            }
        }
        try {
            CommonEventManager.unsubscribeCommonEvent(receiver);
        } catch (IllegalArgumentException | RemoteException e) {
            // Receiver not registered
        }
    }

}
